package com.hsh.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hsh.member.base.Page;
import com.hsh.member.base.Result;
import com.hsh.member.entity.Goods;
import com.hsh.member.entity.Supplier;
import com.hsh.member.mapper.SupplierMapper;
import com.hsh.member.req.SupplierREQ;
import com.hsh.member.service.IGoodsService;
import com.hsh.member.service.ISupplierService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 供应商信息表 服务实现类
 * </p>
 *
 * @author 海上花-www.hsh.com
 * @since 2022-12-01
 */
@Service
public class SupplierServiceImpl extends ServiceImpl<SupplierMapper, Supplier> implements ISupplierService {

    @Override
    public Result search(long page, long size, SupplierREQ req) {
        QueryWrapper<Supplier> query=new QueryWrapper<>();
        if(req!=null){
            if(StringUtils.isNotBlank(req.getName())){
                query.like("name",req.getName());
            }
            if(StringUtils.isNotBlank(req.getLinkman())){
                query.like("linkman",req.getLinkman());
            }
            if(StringUtils.isNotBlank(req.getMobile())){
                query.like("mobile",req.getMobile());
            }
        }
        //分页查询供应商
        Page<Supplier> data = baseMapper.selectPage(new Page<Supplier>(page, size), query);
        return  Result.ok(data);
    }

    @Autowired
    private IGoodsService goodsService;

    @Override
    public Result deleteById(int id) {
        //1.通过供应商id查询是否被商品引用
        List<Goods> goodsList = goodsService.selectBySupplierId(id);
        //2.如果被商品引用，则不让删除供应商
        if(CollectionUtils.isNotEmpty(goodsList)){
            return Result.error("改供应商被商品引用,不允许删除");
        }
        //如果没有被引用 直接删除
        int i = baseMapper.deleteById(id);
        if(i<1){
            return Result.error("删除供应商失败");
        }
        return Result.ok();
    }

    @Override
    public Result update(int id, Supplier supplier) {
       if(supplier.getId() == null){
           supplier.setId(id);
        }
       //更新操作
        int i = baseMapper.updateById(supplier);
       if(i<1){
           return Result.error("修改供应商信息失败");
       }
       return Result.ok();
    }
}
